export default class Snake{
     constructor(map){
         this.map =map

         //蛇
         this.snake =[]


        //方向
         this.direction ='right'

         //初始化蛇
         this.creSnake()
     }

    //1计算蛇头出现的下一个位置
    pos(){

        //只负责计算位置

        //判断 之前有头 出现在0 0 否则根据方向判断
        
        const head = this.snake[0]
        if(!head)  return { left:0, top:0 }
        
        const obj = {
            left:head.offsetLeft,
            top:head.offsetTop
        }
        switch(this.direction){
            case 'top':obj.top -= 20;break
            case 'left':obj.left -= 20;break
            case 'right':obj.left += 20;break
            case 'bottom':obj.top += 20;break
        }

        return obj
    }

    //2给蛇加一个头
    creHead(){
        const pos =this.pos()

        const head = this.snake[0]

        if (head) head.className = 'body'
        const div = document.createElement('div')
        div.className = 'head'
        div.style.left = pos.left + 'px'
        div.style.top = pos.top + 'px'
        this.snake.unshift(div)
        this.map.appendChild(div)

    }   

    //3初始化一个蛇
    creSnake(){
        for(let i=0;i<3;i++){
            this.creHead();
        }
    }

    //4蛇动起来

    move(){
        const body =this.snake.pop()
        body.remove()
        this.creHead()
    }

    //判断是否死亡
    isDie(){
        const head = this.snake[0]
        const x=head.offsetLeft
        const y=head.offsetTop

        //判断

        if(x < 0|| y < 0||x>=this.map.clientWidth||y>=this.map.clientHeight){
            return true
        }
        else{
            const temp = this.snake.slice(1)
            let flag = false
            temp.forEach(item =>{
                if(x=== item.offsetLeft&&y===item.offsetTop){
                    flag = true
                }
            })
            return flag
        }
        


    }

    //判断是否吃到食物
    isEat(food){
        const x = this.snake[0].offsetLeft
        const y = this.snake[0].offsetTop

        if(x===food.x&&y===food.y){
            return true
        }else{
            return false
        }
    }

 }